﻿using CommonLayer;
using DataBaseLayer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using EntitiesLayer.ViewModels;

namespace TSUILayer.Views.Sales
{
    /// <summary>
    /// Interaction logic for JobCardBView.xaml
    /// </summary>
    public partial class JobCardBView : Page
    {
        DataLayer _data = null;
        IEnumerable<DDBinding> _autoSource = null;
        List<JobCardViewModel> lstSpareService = new List<JobCardViewModel>();
        SPARE_PART selectedPart = null;
        JOB_CARD _objJob = null;

        public JobCardBView(ref JobCardBView jobCardBInstance, DataLayer data)
        {
            InitializeComponent();
            _data = data;
            cmbSupplier.ItemsSource = data.GetAllSuppliers(CommonLayer.TYPE.SPARE);
            jobCardBInstance = this;
        }

        public void UpdateJobCardBView(ref JobCardAView objJobCard)
        {
            _objJob = objJobCard.GetObj();
        }

        private void txtSparePartCode_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (_autoSource != null)
            {
                var result = _autoSource.Where(s => s.Name.ToLower().Contains(txtSparePartCode.Text.ToLower()) && !string.IsNullOrEmpty(txtSparePartCode.Text)).Select(s => s);
                lstSugesstions.Visibility = result.Count() <= 0 ? Visibility.Collapsed : Visibility.Visible;
                lstSugesstions.ItemsSource = result;
            }
        }

        private void lstSugesstions_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            txtSparePartCode.TextChanged -= new TextChangedEventHandler(txtSparePartCode_TextChanged);
            if (lstSugesstions.SelectedValue != null)
            {
                txtSparePartCode.Text = (lstSugesstions.SelectedItem as DDBinding).Name;
                selectedPart = _data.GetById<SPARE_PART>(s => s.SPARE_PART_ID == Convert.ToInt32(lstSugesstions.SelectedValue));
            }
            lstSugesstions.Visibility = Visibility.Collapsed;
            txtSparePartCode.TextChanged += new TextChangedEventHandler(txtSparePartCode_TextChanged);
        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            SPARE_PURCHASES_SALE spareSale = new SPARE_PURCHASES_SALE();
            if (selectedPart != null)
            {
                txtSparePartCode.Clear();
                JobCardViewModel spareModel = new JobCardViewModel();
                var result = _data.GetStock(Convert.ToInt32(cmbSupplier.SelectedValue), selectedPart.SPARE_PART_ID);
                spareModel.PartCode = selectedPart.SPARE_PART_CODE;
                spareModel.PartDescription = selectedPart.SPARE_PART_DESCRIPTION;
                spareModel.PartId = selectedPart.SPARE_PART_ID;
                var details = selectedPart.SPARE_PURCHASES_SALEs.First(s => s.SPARE_PART_ID == selectedPart.SPARE_PART_ID);
                spareModel.PriceSource = result.Where(s => s.Stock > 0).Select(s => new DDBinding() { Id = s.Stock, Name = s.UnitCost.ToString() }).ToList();
                spareModel.VatPrecent = details.VAT_PERCENT;

                lstSpareService.Add(spareModel);
                gridSpareService.ItemsSource = lstSpareService;
                gridSpareService.Items.Refresh();
                selectedPart = null;
            }
        }

        #region - UI Validations.
        private void NumericOnly(System.Object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            e.Handled = IsTextNumeric(e.Text);
        }
        private static bool IsTextNumeric(string str)
        {
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[^0-9]");
            return reg.IsMatch(str);

        }


        private void AlphabetOnly(System.Object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            e.Handled = IsAlphabet(e.Text);
        }
        private static bool IsAlphabet(string str)
        {
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[^A-Za-z]");
            return reg.IsMatch(str);
        }


        private void FloatingPointOnly(System.Object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            e.Handled = IsFloatingPointvalue(e.Text);
        }
        private static bool IsFloatingPointvalue(string str)
        {
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[^0-9.-]");
            return reg.IsMatch(str);
        }


        private void AlphaNumerictOnly(System.Object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            e.Handled = IsAlphaNumeric(e.Text);
        }
        private static bool IsAlphaNumeric(string str)
        {
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[^a-zA-Z0-9]");
            return reg.IsMatch(str);
        }
        #endregion - UI Validations.

        private void txtValue_TextChanged(object sender, TextChangedEventArgs e)
        {
            var textBox = (sender as TextBox);
            var selectedRow = gridSpareService.CurrentItem as JobCardViewModel;

            if (selectedRow is JobCardViewModel)
            {
                var vatAmount = selectedRow.UnitPrice * (selectedRow.VatPrecent / Convert.ToDecimal(selectedRow.VatPrecent == decimal.Parse("5.5") ? 105.5 : 114.5));
                if (textBox != null)
                    selectedRow.Quantity = Convert.ToInt32(string.IsNullOrEmpty(textBox.Text) ? "0" : textBox.Text);
                selectedRow.Value = decimal.Round(selectedRow.UnitPrice - (vatAmount * selectedRow.Quantity), 2);
                selectedRow.TotalAmount = decimal.Round((selectedRow.UnitPrice * selectedRow.Quantity), 2);
            }

            lblTotal.Content = decimal.Round(lstSpareService.Sum(s => s.TotalAmount), 2);
            CalculateTotal(null, null);
        }

        private void chkWarranty_Click(object sender, RoutedEventArgs e)
        {
            var selectedRow = gridSpareService.CurrentItem as JobCardViewModel;
            if (selectedRow is JobCardViewModel)
            {
                selectedRow.IsWCEnabled = (sender as CheckBox).IsChecked.Value;
                selectedRow.WCNo = string.Empty;
            }
            lblWarrantyAmount.Content = decimal.Round(lstSpareService.Where(s => s.IsWarrantty).Sum(s => s.TotalAmount), 2);
            CalculateTotal(null, null);
        }

        private void btnBack_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.GoBack();
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {            
            _objJob.LABOUR_CHARGE = Convert.ToDecimal(txtLabourCharge.Text);
            _objJob.OTHER_REPAIRS = Convert.ToDecimal(txtOtherRepairCharge.Text);
            _objJob.WASHING_CHARGE = Convert.ToDecimal(txtWashingCharge.Text);
            _objJob.SALES_INVOICE.INVOICE_GRANDTOTAL = Convert.ToDecimal(lblGrandTotal.Content);
            lstSpareService.ForEach(s =>
            {
                _objJob.SALES_INVOICE.SPARE_PURCHASES_SALEs.Add(new SPARE_PURCHASES_SALE()
                        {
                            SPARE_PART = _data.GetById<SPARE_PART>(sp => sp.SPARE_PART_ID == s.PartId),
                            SPARE_UNIT_COST = s.UnitPrice,
                            VAT_PERCENT = s.VatPrecent,
                            QUANTITY = s.Quantity,
                            IS_WARRANTY = s.IsWarrantty,
                            SUB_TOTAL = s.TotalAmount,
                            WC_NO = s.WCNo,
                            SUPPLIER_ID = Convert.ToInt32(cmbSupplier.SelectedValue),
                            TRANSACTION_TYPE=_data.GetMasterId(CommonLayer.TRANSACTIONTYPE.SALE.ToString()),
                            SPARE_TYPE = _data.GetMasterId(CommonLayer.SPARETYPE.ITEMS.ToString())                            
                        });
            });
            _data.Insert<SALES_INVOICE>(_objJob.SALES_INVOICE);
            MessageBox.Show("Invoice Generated Successfully.");
        }

        private void cmbSupplier_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _autoSource = _data.GetAll<SPARE_PART>(s => s.MASTER.MASTER_VALUE.Equals(CommonLayer.STATUS.ACTIVE))
               .Join(_data.GetAll<SPARE_PURCHASES_SALE>(s => s.SUPPLIER_ID == Convert.ToInt32(cmbSupplier.SelectedValue)), sp => sp.SPARE_PART_ID, sr => sr.SPARE_PART_ID, (a, b) => a)
               .GroupBy(s => s.SPARE_PART_CODE, (a, b) => new CommonLayer.DDBinding() { Id = b.First().SPARE_PART_ID, Name = a });
        }

        private void cmbPriceSource_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selectedRow = gridSpareService.CurrentItem as JobCardViewModel;
            if (selectedRow is JobCardViewModel)
            {
                selectedRow.UnitPrice = Convert.ToDecimal(((sender as ComboBox).SelectedItem as DDBinding).Name);
                txtValue_TextChanged(null, null);
            }
        }

        void CalculateTotal(object sender, TextChangedEventArgs e)
        {
            decimal grandTotal = 0;

            if (!string.IsNullOrEmpty(txtWashingCharge.Text))
                grandTotal += Convert.ToDecimal(txtWashingCharge.Text);
            if (!string.IsNullOrEmpty(txtOtherRepairCharge.Text))
                grandTotal += Convert.ToDecimal(txtOtherRepairCharge.Text);
            if (!string.IsNullOrEmpty(txtLabourCharge.Text))
                grandTotal += Convert.ToDecimal(txtLabourCharge.Text);
            if (lblTotal.Content != null)
                grandTotal += Convert.ToDecimal(lblTotal.Content);
            if (lblWarrantyAmount.Content != null)
                grandTotal -= Convert.ToDecimal(lblWarrantyAmount.Content);

            lblGrandTotal.Content = grandTotal;
        }
    }
}
